# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import tools
from odoo import api, fields, models
import odoo.addons.decimal_precision as dp


class SaleOrderLineExtend(models.Model):
    _name = 'sale.order.line'
    _inherit = 'sale.order.line'

    qty_invoiced_with_done = fields.Float(
        compute='_get_invoice_qty_with_validate', string='Validate Invoiced', store=True, readonly=True,
        digits=dp.get_precision('Product Unit of Measure'))

    @api.depends('invoice_lines.invoice_id.state', 'invoice_lines.quantity')
    def _get_invoice_qty_with_validate(self):
        for line in self:
            qty_invoiced = 0.0
            for invoice_line in line.invoice_lines:
                if invoice_line.invoice_id.state in ('open', 'paid'):
                    if invoice_line.invoice_id.type == 'out_invoice':
                        qty_invoiced += invoice_line.uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
                    elif invoice_line.invoice_id.type == 'out_refund':
                        qty_invoiced -= invoice_line.uom_id._compute_quantity(invoice_line.quantity, line.product_uom)
            line.qty_invoiced_with_done = qty_invoiced


class SalesDetailReport(models.Model):
    _name = "sales.detail.report"
    _description = "Sales Detail Report"
    _auto = False
    _order = 'name desc'

    project_id = fields.Many2one('account.analytic.account', u'分析账户', readonly=True)
    name = fields.Char(u'SO单号', readonly=True)
    product_id = fields.Many2one('product.product', u'产品', readonly=True)
    date_order = fields.Datetime(u'SO日期', readonly=True)
    partner_id = fields.Many2one('res.partner', u'客户名称', readonly=True)
    team_id = fields.Many2one('crm.team', u'部门', readonly=True)
    user_id = fields.Many2one('res.users',u'业务员', readonly=True)
    product_uom_qty = fields.Float(u'销售订单数量', readonly=True)
    amt_notax = fields.Float(u'销售单价(不含税)', readonly=True)
    amt_taxed = fields.Float(u'销售单价(含税)', readonly=True)
    price_subtotal = fields.Float(u'销售总金额(不含税)', readonly=True)
    price_total = fields.Float(u'销售总金额(含税)', readonly=True)
    wait_out_qty = fields.Float(u'待出库数量', readonly=True)
    qty_invoiced = fields.Float(u'已开发票数量', readonly=True)
    invoiced_amt = fields.Float(u'已开发票金额(含税)', readonly=True)
    wait_inv_amt = fields.Float(u'待开发票金额(含税)', readonly=True)


    @api.model_cr
    def init(self):
        tools.drop_view_if_exists(self.env.cr, self._table)
        self.env.cr.execute("""CREATE or REPLACE VIEW %s as (
SELECT id,
       project_id,
       name,
       product_id,
       date_order,
       partner_id,
       team_id,
       user_id,
       product_uom_qty,
       amt_taxed,
       amt_notax,
       price_subtotal,
       price_total,
       qty_invoiced,
       product_uom_qty - sum(out_qty) + rtn_qty                       AS wait_out_qty,
       CASE
         WHEN type = 'service'
         THEN (product_uom_qty - rtn_qty - qty_invoiced) * amt_taxed
         ELSE (sum(out_qty) - rtn_qty - qty_invoiced) * amt_taxed END AS wait_inv_amt,
       qty_invoiced * amt_taxed                                       AS invoiced_amt
FROM (SELECT id,
             project_id,
             name,
             product_id,
             date_order,
             partner_id,
             team_id,
             user_id,
             product_uom_qty,
             amt_taxed,
             amt_notax,
             price_subtotal,
             price_total,
             qty_invoiced,
             out_id,
             out_qty,
             type,
             sum(rtn_qty) as rtn_qty
      FROM (SELECT sol.id,
                   so.project_id,
                   so.name,
                   sol.product_id,
                   so.date_order,
                   so.partner_id,
                   so.team_id,
                   so.user_id,
                   sol.product_uom_qty,
                   pt.type,
                   CASE
                     WHEN sol.product_uom_qty = 0 THEN 0
                     ELSE sol.price_total / sol.product_uom_qty END    AS amt_taxed,
                   CASE
                     WHEN sol.product_uom_qty = 0 THEN 0
                     ELSE sol.price_subtotal / sol.product_uom_qty END AS amt_notax,
                   sol.price_subtotal,
                   sol.price_total,
                   coalesce(outsm.id, 0)                               as out_id,
                   coalesce(outsm.product_qty, 0)                      AS out_qty,
                   coalesce(rtnsm.product_qty, 0)                      AS rtn_qty,
                   sol.qty_invoiced_with_done                          AS qty_invoiced
            FROM sale_order so
                   INNER JOIN sale_order_line sol ON so.id = sol.order_id
                   INNER JOIN product_product pp ON sol.product_id = pp.id
                   INNER JOIN product_template pt ON pp.product_tmpl_id = pt.id
                   LEFT JOIN stock_picking sp ON sp.origin = so.name
                   LEFT JOIN stock_move outsm ON sp.id = outsm.picking_id and sol.product_id = outsm.product_id
                   LEFT JOIN stock_move rtnsm
                     ON outsm.id = rtnsm.origin_returned_move_id and outsm.product_id = rtnsm.product_id
            WHERE so.state IN ('sale', 'done')) A
      GROUP BY id,
               project_id,
               name,
               product_id,
               date_order,
               partner_id,
               team_id,
               user_id,
               product_uom_qty,
               amt_taxed,
               amt_notax,
               price_subtotal,
               price_total,
               qty_invoiced,
               out_qty,
               type,
               out_id) B
GROUP BY id,
         project_id,
         name,
         product_id,
         date_order,
         partner_id,
         team_id,
         user_id,
         product_uom_qty,
         amt_taxed,
         amt_notax,
         price_subtotal,
         price_total,
         qty_invoiced,
         rtn_qty,
         type
            )""" % self._table)
